import { fetchReview } from '../../../services/reviews/fetchReview';
import { updateLiker, addLook }  from '../../../services/reviews/fetchReview';
import { cdnBase } from '../../../config/index';

const imgPrefix = `${cdnBase}/`;

const recLeftImg = `${imgPrefix}common/rec-left.png`;
const recRightImg = `${imgPrefix}common/rec-right.png`;
const obj2Params = (obj = {}, encode = false) => {
  const result = [];
  Object.keys(obj).forEach((key) =>
    result.push(`${key}=${encode ? encodeURIComponent(obj[key]) : obj[key]}`),
  );

  return result.join('&');
};

Page({
  data: {
    author: '',
    avatar: '',
    isShowPromotionPop: false,
    recLeftImg,
    recRightImg,
    details: {},
    buttonType: 1,
    selectedAttrStr: '',
    skuArray: [],
    primaryImage: '',
    specImg: '',
    isSpuSelectPopupShow: false,
    isAllSelectedSku: false,
    spuId: '',
    current: 0,
    autoplay: true,
    duration: 500,
    interval: 5000,
    list: [],
    navigation: { type: 'fraction' },
    previewVisible: false,
    swiperImagesIndex: 0,
    icon_name: "heart",
    icon_color: "black",
  },

  handleImagePreview(e) {
    const {index} = e.detail;
    this.setData({
      previewVisible: true,
      swiperImagesIndex: index
    });
  },

  handleImagePreviewClose() {
    this.setData({
      previewVisible: false,
      swiperImagesIndex: 0
    });
  },

  handlePopupHide() {
    this.setData({
      isSpuSelectPopupShow: false,
    });
  },

  showPromotionPopup() {
    this.setData({
      isShowPromotionPop: true,
    });
  },

  closePromotionPopup() {
    this.setData({
      isShowPromotionPop: false,
    });
  },

  toNav(e) {
    const { url } = e.detail;
    console.log(url);
    wx.switchTab({
      url: url,
    });
  },

  showCurImg(e) {
    const { index } = e.detail;
    const { images } = this.data.details;
    wx.previewImage({
      current: images[index],
      urls: images, // 需要预览的图片http链接列表
    });
  },

  /* 这里以后做comments里再弄 */
  // onPageScroll({ scrollTop }) {
  //   const goodsTab = this.selectComponent('#goodsTab');
  //   goodsTab && goodsTab.onScroll(scrollTop);
  // },
  getDetail(spuId) {
    Promise.resolve(fetchReview(spuId, true)).then((data) => {
      const details = data;
      if (details.liked) {
        this.setData({
          icon_name: 'heart-filled',
          icon_color: 'red',
          details,
        })
      } else {
        this.setData({
          details,
        });
      }
    });
  },

  addLookup(spuId) {
    Promise.resolve(addLook(spuId)).then((data) => {
      const isSuccess = data.result;
      if (isSuccess)
        console.log('Listen the reviews of lookup success.')
    });
  },

  likerPlusHandle() {
    const { details } = this.data;
    let user_id = wx.getStorageSync('user_id');
    let liked = details.liked;
    let likerNum = details.liker_num;
    let post_data = {
      reviews_id: details.reviews_id,
      user_id: user_id,
      liker_num: 0,
      method: ''
    };

    if (liked) {
      likerNum--;
      post_data.liker_num = likerNum;
      post_data.method = 'minus';

      details.liker_num = likerNum;
      this.setData({
        icon_name: 'heart',
        icon_color: 'black',
        details,
      })
    } else {
      likerNum++;
      post_data.liker_num = likerNum;
      post_data.method = 'plus';

      details.liker_num = likerNum;
      this.setData({
        icon_name: 'heart-filled',
        icon_color: 'red',
        details,
      })
    }

    updateLiker(post_data).then((data) => {
      wx.showToast({
        title: "喜欢列表更新",
        icon: "none",
        duration: 2000
      });
    });
  },

  onLoad(query) {
    const { spuId } = query;
    console.log('spuId: ' + spuId)
    this.setData({
      spuId: spuId,
    });
    this.getDetail(spuId);
    this.addLookup(spuId);

    // this.getCommentsList(spuId);
    // this.getCommentsStatistics(spuId);
  },

  scrollText(componentId) {
    wx.createSelectorQuery().select(componentId).boundingClientRect((res) => {
      const textWidth = res.width; // 获取文本宽度
      const containerWidth = res.width; // 获取容器宽度
      const scrollDistance = textWidth - containerWidth; // 计算需要滚动的距离

      if (scrollDistance > 0) {
        const scrollAnimation = wx.createAnimation({
          duration: 5000, // 滚动持续时间
          timingFunction: 'linear', // 动画以线性方式进行
        });

        const scroll = (distance) => {
          scrollAnimation.translateX(-distance).step();
          this.setData({
            animationData: scrollAnimation.export(),
          });

          if (distance > 0) {
            setTimeout(() => {
              scroll(distance - containerWidth);
            }, 100); // 调整时间以控制滚动速度
          }
        };

        scroll(scrollDistance); // 开始滚动
      }

    }).exec(res => {
      console.log(res)
    })
  },
});